package cn.tedu.dao;

import cn.tedu.pojo.User;
import cn.tedu.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDAOImpl implements UserDAO{
    @Override
    public List<User> findAll() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<>();
        try {
            conn = JDBCUtil.getConnection();
            String sql = "select * from user3";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                /*User user = new User(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("username"),
                        rs.getString("password"));*/
                User user = getUser(rs);
                userList.add(user);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.close(conn,ps,rs);
        }
        return userList;
    }

    private User getUser(ResultSet rs) throws SQLException {
        User user = new User(
                rs.getInt("id"),
                rs.getString("name"),
                rs.getString("username"),
                rs.getString("password"));
        return user;
    }

    @Override
    public List<User> findByLikeName(String name) {
        return null;
    }

    @Override
    public User findUserByUP(String username, String password) {
        return null;
    }

    @Override
    public User findUserById(int id) {
        return null;
    }

    @Override
    public int insert(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        int row = -1;
        try {
            conn = JDBCUtil.getConnection();
            String sql = "insert into user(name,username,password) values(?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getName());
            ps.setString(2,user.getUsername());
            ps.setString(3,user.getPassword());
            row = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.close(conn,ps,null);
        }
        return row;
    }

    @Override
    public int delete(int id) {
        return 0;
    }

    @Override
    public int update(User user) {
        return 0;
    }
}
